package arrAndstr;

public class T151 {

    public static void main(String[] args) {
        String s = "the sky is blue";
        System.out.println(reverseWords(s));
    }

    public static String reverseWords(String s) {
        StringBuffer sb = new StringBuffer("");
        int len = s.length();
        int leftIndex = 0;
        int rightIndex = 0;

        for(int i=len-1; i>=0; i--) {
            char ch = s.charAt(i);
            if(ch != ' ' && (i+1 >= len || s.charAt(i+1) == ' ')) {  // 单词尾
                rightIndex = i;
            }
            if(ch != ' ' && (i-1 < 0 || s.charAt(i-1) == ' ')) {    // 单词首
                leftIndex = i;
                sb.append(s.substring(leftIndex, rightIndex+1));
                sb.append(" ");
            }
        }
        return sb.toString().substring(0, sb.length()-1);
    }
}
